package cn.my.learning.service;

import cn.my.learning.domain.ExternalLink;
import cn.my.learning.domain.ExternalLinkList;
import cn.my.learning.repository.ExternalLinkListRepository;
import cn.my.learning.repository.ExternalLinkRepository;
import cn.my.learning.util.PageableTools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Created by Leo on 2017/4/9.
 * 外链服务层
 */
@Repository
public class ExternalLinkServiceImpl {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private ExternalLinkRepository externalLinkRepository;

    @Autowired
    private ExternalLinkListRepository externalLinkListRepository;

    private static final Logger logger = LoggerFactory.getLogger(ExternalLinkServiceImpl.class);

    /**
     * 通过libraryCode查询
     * @param libraryCode
     * @return List
     */
    public List<ExternalLink> findByLibraryCode(String libraryCode){
        Query query = Query.query(Criteria.where("libraryCode").is(libraryCode));
        return mongoTemplate.find(query, ExternalLink.class);
    }

    /**
     * 通过libraryCode查询
     * @param libraryCode
     * @return List
     */
    public Page<ExternalLinkList> findByLibraryCodeList(String libraryCode,Integer current,Integer size){
        Pageable pageable = PageableTools.addLibraryDateSortForDesc(current, size);
        return externalLinkListRepository.findBylibraryCode(libraryCode, pageable);
    }

    /**
     * 分页查询所有外链
     * @param libraryType
     * @param current
     * @param size
     * @return
     */
    public Page<ExternalLink> findAllExternalLink(String libraryType,Integer current,Integer size){
        Pageable pageable = PageableTools.addLibraryDateSortForDesc(current, size);
        if(libraryType.equals("")) {
            return externalLinkRepository.findAll(pageable);
        }else{
            return externalLinkRepository.findBylibraryType(libraryType,pageable);
        }
    }

    /**
     * 分页查询所有外链Name（带分页以及模糊查询）
     * @param articleTitle
     * @param current
     * @param size
     * @return
     */
    public Page<ExternalLinkList> findExternalLinkListByArticleTitle(String articleTitle, Integer current, Integer size){
        Pageable pageable = PageableTools.normalSort(current, size);
        return externalLinkListRepository.findByArticleTitleLike(articleTitle, pageable);
    }
}
